<template>
  <el-dialog
    class="subject-status-add-record"
    :title="dialogTitle"
    width="600px"
    :show-close="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div>
      <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
        <el-form-item label="是否生效：">
          <el-radio-group v-model="formData.takeEffect">
            <el-radio :label="1">生效</el-radio>
            <el-radio :label="0">失效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="变量取值：">
          <el-select
            size="mini"
            v-model="formData.variableValue"
            placeholder="请选择"
            style="width: 80%"
            v-if="['10', '20'].includes(formData.variableType)"
          >
            <el-option
              v-for="item in variableValueOptions"
              :key="item.codeValue"
              :value="item.codeValue"
              :label="item.codeDescribe"
            ></el-option>
          </el-select>
          <el-input v-model="formData.variableValue" placeholder="请输入" style="width: 80%" v-else></el-input>
        </el-form-item>
        <el-form-item label="当前变量：">
          <el-select size="mini" v-model="formData.currentVariable" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in currentVariableList"
              :key="item.variable"
              :value="item.variable"
              :label="item.variableName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比较方法：">
          <el-select size="mini" v-model="formData.method" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in compareTypeList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比较表：">
          <el-select
            size="mini"
            v-model="formData.comparisonTable"
            placeholder="请选择"
            style="width: 80%"
            @change="handleTableChange"
          >
            <el-option v-for="item in eCRFDesignList" :key="item.surface" :value="item.surface">
              <span style="float: left">{{ item.surfaceName }}({{ item.surface }})</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比较变量：">
          <el-select size="mini" v-model="formData.compareVariables" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in compareVariableList"
              :key="item.variable"
              :value="item.variable"
              :label="item.variableName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="聚合函数：">
          <el-radio-group v-model="formData.aggregation">
            <el-radio label="1">最小</el-radio>
            <el-radio label="2">最大</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="聚合范围：">
          <el-radio-group v-model="formData.aggregationScope">
            <el-radio label="1">表单级别</el-radio>
            <el-radio label="2">受试者级别</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="质疑方式：">
          <el-select size="mini" v-model="formData.way" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in questioningModeList"
              :key="item.value"
              :value="item.value"
              :label="item.text"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogTitle === '复制'">
          <p style="color: red"><i class="el-icon-info"></i>复制前请先修改数据！</p>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'
import { compareTypeList } from '@/utils/enums/ecrf-design.js'

export default {
  props: {
    editData: Object,
    dialogVisible: Boolean,
    dialogTitle: String,
    questioningModeList: Array,
    searchParams: Object,
    eCRFDesignList: Array,
  },
  data() {
    return {
      rules: {},
      loading: false,
      defaultFormData: {},
      formData: {
        takeEffect: '',
      },
      compareTypeList,
      compareVariableList: [],
      currentVariableList: [],
      projectId: '',
      databaseId: '',
      databaseVersion: '',
      variableValueOptions: [],
    }
  },

  watch: {
    dialogVisible(val) {
      if (val) {
        this.formData = this.editData.id ? { ...this.editData } : { ...this.defaultFormData }
        this.getCurrentVariableList()
        this.getVariableValueOptions()
      } else {
        this.formData = { ...this.defaultFormData }
      }
    },
  },

  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.databaseId = this.databaseInfo.databaseId || ''
    this.databaseVersion = this.databaseInfo.databaseVersion || ''
  },

  methods: {
    ...mapActions('verificationRule', ['copyCustomAggregation', 'editCustomAggregation', 'qryCurrentVariableList']),
    ...mapActions('eCRFDesign', ['qryVariableConfigListNoLoading', 'qryCodeValueByCodeNameNoLoading']),

    // 变量取值选项下拉选项
    async getVariableValueOptions() {
      const params = {
        projectId: this.projectId,
        databaseId: this.databaseId,
        databaseVersion: this.databaseVersion,
        code_name: this.editData.variable,
        surface: this.editData.surface,
      }
      const res = await this.qryCodeValueByCodeNameNoLoading({ params })
      this.variableValueOptions = res.data
    },

    // 关闭取消
    handleClose() {
      this.formData = { ...this.defaultFormData }
      this.$emit('handleCancel')
    },

    // 保存提交
    handleSave() {
      this.loading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogTitle === '编辑') {
            const data = {
              reqDTOList: [{ ...this.formData }],
            }
            this.editCustomAggregation({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          } else {
            const data = {
              ...this.formData,
            }
            this.copyCustomAggregation({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          }
        } else {
          this.loading = false
          return false
        }
      })
    },

    // 获取当前变量列表
    getCurrentVariableList() {
      const params = {
        ...this.searchParams,
      }
      this.qryCurrentVariableList({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.currentVariableList = data
        }
      })
    },

    // 获取比较变量
    handleTableChange(value) {
      if (value) {
        this.getVariableList(value)
      }
    },

    // 查询比较变量
    getVariableList(surface) {
      const params = {
        ...this.searchParams,
        surface,
      }
      this.qryVariableConfigListNoLoading({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.compareVariableList = data
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './add-record.scss';
</style>
